<template>
    <div class="container" ref="container">
      <div v-for="item in items" :key="item" class="item">
        {{ item }}
      </div>
      <div v-if="loading" class="loading">Loading...</div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        items: [],
        page: 1,
        loading: false,
      };
    },
    mounted() {
      this.loadMoreItems();
      window.addEventListener('scroll', this.handleScroll);
    },
    beforeDestroy() {
      window.removeEventListener('scroll', this.handleScroll);
    },
    methods: {
      async loadMoreItems() {
        if (this.loading) return;
        this.loading = true;
  
        try {
          // 模拟异步请求
          await new Promise((resolve) => setTimeout(resolve, 1000));
  
          const newItems = Array.from({ length: 12 }, (_, i) => `Item ${(this.page - 1) * 12 + i + 1}`);
          this.items.push(...newItems);
  
          this.page++;
          this.loading = false;
        } catch (error) {
          console.error('Error loading items:', error);
          this.loading = false;
        }
      },
      handleScroll() {
        const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
  
        if (scrollTop + clientHeight >= scrollHeight - 100) {
          this.loadMoreItems();
        }
      },
    },
  };
  </script>
  
  <style scoped>
  .container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 10px;
  }
  
  .item {
    width: calc(16.66% - 10px); /* 每行六个盒子，减去间隙 */
    height: 200px;
    background-color: #e0e0e0;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    box-sizing: border-box;
  }
  
  .loading {
    width: 100%;
    text-align: center;
    margin: 20px 0;
  }
  </style>
  